import { VideoPlayer, Button, Image } from '@douyinfe/semi-ui';
import { Message } from '@arco-design/web-react';
import { forwardRef, useEffect, useCallback, useState, useRef } from 'react';
import deleteIcon from '@/assets/images/imageEdit/delete.svg';
import download from '@/assets/images/imageEdit/download.svg';
import copy from '@/assets/images/imageEdit/copy.svg';
import styles from './index.module.scss';
import sharedWebSocket from '@/services/sharedWebSocket.jsx';
import { useLoading } from '@/components/common/mlsLoading/laodingText';
import { synthesisHistoryListGet, synthesisHistoryListDelete } from '@/api/common.jsx';
import { downloadMedia } from '@/utils/common.jsx';
import VideoPlaceholder from './videoPlaceholder.jsx';

/**
 * 通用视频历史组件
 * @param {Object} props - 组件属性
 * @param {React.Ref} ref - 组件引用
 * @param {Array} props.resultsItemRefs - 结果项引用数组
 * @param {string} props.currentMenuTitle - 当前菜单标题
 * @param {Function} props.passVideoHistoryList - 传递视频历史列表的回调函数
 * @param {string} props.operType - 操作类型（textToVideo, imgToVideo, frameToVideo等）
 * @param {Array} props.customButtons - 自定义按钮配置
 * @param {Function} props.onItemClick - 项目点击回调
 * @param {Object} props.additionalFields - 额外字段映射配置
 * @param {boolean} props.enableSocket - 是否启用WebSocket监听
 */
const VideoHistory = forwardRef(
  (
    {
      resultsItemRefs,
      currentMenuTitle,
      passVideoHistoryList,
      operType = 'textToVideo',
      customButtons = [],
      onItemClick,
      additionalFields = {},
      enableSocket = true,
    },
    ref
  ) => {
    const [videoHistoryList, setVideoHistoryList] = useState([]);
    const [playingVideoId, setPlayingVideoId] = useState(null); // 新增：当前播放的视频ID
    const { showLoading, hideLoading } = useLoading();

    // 新增：存储所有视频播放器实例的ref
    const videoPlayerRefs = useRef(new Map());

    // 默认按钮配置
    const DEFAULT_BUTTONS = [
      {
        type: 'download',
        icon: download,
        text: '下载',
      },
      {
        type: 'delete',
        icon: deleteIcon,
        text: '删除',
      },
    ];

    // 合并自定义按钮和默认按钮
    const BTN_TYPE = [...DEFAULT_BUTTONS, ...customButtons];

    // 操作类型映射
    const OPER_TYPE_MAP = {
      textToVideo: '文生视频',
      imgToVideo: '图生视频',
      mutiImgToVideo: '首尾帧生视频',
      videoPost: '视频后处理',
    };

    /**
     * 处理文本复制到剪切板
     * @param {string} text - 要复制的文本
     */
    const handleCopyText = useCallback(async text => {
      try {
        await navigator.clipboard.writeText(text);
        Message.success('文本已复制到剪切板');
      } catch (error) {
        console.error('复制失败:', error);
        Message.error('复制失败，请手动复制');
      }
    }, []);

    /**
     * 获取视频历史列表
     */
    const fetchVideoList = useCallback(async () => {
      showLoading('加载中...');
      try {
        const res = await synthesisHistoryListGet({ operType, pageSize: 1000 });
        if (res?.code === 200) {
          const list = (res?.data?.list || []).map(item => {
            const operInfo = item.operInfo ? JSON.parse(item.operInfo) : {};

            // 基础字段映射
            const baseFields = {
              videoUrl: item.fileUrl,
              apiName: operInfo.apiName || '',
              ratio: operInfo.ratio || '',
              resolution: operInfo.resolution || '',
              text: operInfo.text || '',
              firstFrameUrl: operInfo.firstFrameUrl || '',
              title: item.title || OPER_TYPE_MAP[operType] || '视频生成',
              historyId: item.historyId,
              time: item.createTime || '',
            };

            // 合并额外字段
            const additionalData = {};
            Object.keys(additionalFields).forEach(key => {
              additionalData[key] = operInfo[additionalFields[key]] || '';
            });

            return { ...baseFields, ...additionalData };
          });

          setVideoHistoryList(list);
          passVideoHistoryList?.(list);
        }
      } catch (error) {
        console.error('获取视频历史列表失败:', error);
        Message.error('获取历史记录失败');
      } finally {
        hideLoading();
      }
    }, [operType, passVideoHistoryList]);

    /**
     * 处理操作按钮点击
     * @param {string} type - 操作类型
     * @param {Object} item - 当前项目数据
     */
    const handleOptClick = useCallback(
      async (type, item) => {
        try {
          switch (type) {
            case 'delete':
              const res = await synthesisHistoryListDelete({ historyId: item.historyId });
              if (res?.code === 200) {
                Message.success('删除成功');
                fetchVideoList();
              }
              break;
            case 'download':
              downloadMedia(item.videoUrl);
              break;
            default:
              // 处理自定义按钮操作
              console.log('自定义操作:', type, item);
              break;
          }
        } catch (error) {
          console.error('操作失败:', error);
          Message.error('操作失败');
        }
      },
      [fetchVideoList]
    );

    /**
     * 处理项目点击
     * @param {Object} item - 点击的项目数据
     */
    const handleItemClick = useCallback(
      item => {
        onItemClick?.(item);
      },
      [onItemClick]
    );

    /**
     * 处理视频播放状态变化
     * @param {string} videoId - 视频ID
     * @param {boolean} isPlaying - 是否正在播放
     */
    const handleVideoPlay = useCallback(
      (videoId, isPlaying) => {
        console.log(`视频 ${videoId} 播放状态:`, isPlaying);

        if (isPlaying) {
          // 如果有其他视频正在播放，先暂停它
          if (playingVideoId && playingVideoId !== videoId) {
            // 这里可以通过refs获取其他视频播放器实例并暂停
            const playingVideoPlayer = videoPlayerRefs.current.get(playingVideoId);
            console.log('playingVideoPlayer', playingVideoPlayer);
            if (playingVideoPlayer && (playingVideoPlayer.pause || playingVideoPlayer.handlePause)) {
              playingVideoPlayer.pause?.();
              playingVideoPlayer.handlePause?.();
              console.log(`已暂停视频: ${playingVideoId}`);
            }
          }
          setPlayingVideoId(videoId);
        } else {
          setPlayingVideoId(null);
        }
      },
      [playingVideoId]
    );

    /**
     * 优化视频播放器渲染 - 只渲染可见区域的视频
     * 使用Intersection Observer实现懒加载
     */
    const [visibleVideos, setVisibleVideos] = useState(new Set());

    useEffect(() => {
      const observer = new IntersectionObserver(
        entries => {
          entries.forEach(entry => {
            const videoId = entry.target.dataset.videoId;
            if (entry.isIntersecting) {
              setVisibleVideos(prev => new Set([...prev, videoId]));
            } else {
              setVisibleVideos(prev => {
                const newSet = new Set(prev);
                newSet.delete(videoId);
                return newSet;
              });
            }
          });
        },
        {
          rootMargin: '100px 0px', // 预加载100px范围内的视频
          threshold: 0.1,
        }
      );

      // 使用requestAnimationFrame确保DOM更新完成
      requestAnimationFrame(() => {
        const videoContainers = document.querySelectorAll('[data-video-id]');
        videoContainers.forEach(container => {
          if (container.dataset.videoId) {
            observer.observe(container);
          }
        });
      });

      return () => observer.disconnect();
    }, [videoHistoryList]);

    // 初始化加载数据
    useEffect(() => {
      fetchVideoList();
    }, []);

    // WebSocket监听
    useEffect(() => {
      if (!enableSocket) return;

      const handleSocketMessage = data => {
        console.log('handleSocketMessage', data);
        const successEvents = {
          textToVideo: 'text_to_video_success',
          imgToVideo: 'img_to_video_success',
          mutiImgToVideo: 'muti_img_to_video_success',
        };

        const failEvents = {
          textToVideo: 'text_to_video_fail',
          imgToVideo: 'img_to_video_fail',
          mutiImgToVideo: 'muti_img_to_video_fail',
        };

        if (data?.func === successEvents[operType]) {
          hideLoading();
          fetchVideoList();
        }

        if (data?.func === failEvents[operType]) {
          hideLoading();
          Message.error('生成失败');
        }
      };

      sharedWebSocket.on('resp', handleSocketMessage);
      return () => {
        sharedWebSocket.off('resp', handleSocketMessage);
      };
    }, [operType, enableSocket, hideLoading, fetchVideoList]);

    return (
      <div className={styles.videoHistory} ref={ref}>
        {videoHistoryList.map((item, index) => {
          const isVisible = visibleVideos.has(String(item.historyId));

          return (
            <div
              key={item.historyId || index}
              className={styles.videoHistoryItem}
              ref={el => (resultsItemRefs.current[index] = el)}
              onClick={() => handleItemClick(item)}
              data-video-id={item.historyId}>
              {/* 头部信息 */}
              <div className={styles.videoHistoryHead}>
                <div className={styles.videoHistoryHeadLeft}>
                  <div className={styles.videoHistoryTitle}>{item.title}</div>
                  <div className={styles.separator}></div>
                  <div className={styles.videoHistoryMeta}>
                    {operType === 'imgToVideo' && item.referImages && (
                      <div className={styles.thumbnail}>
                        {
                          item.referImages.map((img, index) => (
                            <Image
                              key={index}
                              className={styles.img}
                              src={img.imageUrl}
                              preview={false}
                              draggable={false}
                            />
                          ))
                        }
                        <span>参考图</span>
                      </div>
                    )}
                    {operType === 'mutiImgToVideo' && item.firstFrameUrl && item.endFrameUrl && (
                      <div className={styles.thumbnail}>
                        <Image
                          className={styles.img}
                          src={item.firstFrameUrl}
                          preview={false}
                          draggable={false}
                        />
                        <span>首尾帧</span>
                        <Image
                          className={styles.img}
                          src={item.endFrameUrl}
                          preview={false}
                          draggable={false}
                        />
                      </div>
                    )}
                    {item.apiName && <div className={styles.metaTag}>{item.apiName}</div>}
                    {item.resolution && <div className={styles.metaTag}>{item.resolution}</div>}
                    {item.ratio && <div className={styles.metaTag}>{item.ratio}</div>}
                    {/* 渲染额外字段 */}
                    {/* {Object.keys(additionalFields).map(
                      key =>
                        item[key] && (
                          <div key={key} className={styles.metaTag}>
                            {item[key]}
                          </div>
                        )
                    )} */}
                  </div>
                </div>
                {item.time && <div className={styles.videoHistoryTime}>{item.time}</div>}
              </div>

              {/* 内容区域 */}
              {item.text && (
                <div className={styles.videoHistoryContent}>
                  {item.text}
                  <Image
                    className={styles.copyIcon}
                    src={copy}
                    preview={false}
                    draggable={false}
                    onClick={e => {
                      e.stopPropagation(); // 阻止事件冒泡
                      handleCopyText(item.text);
                    }}
                  />
                </div>
              )}

              {/* 视频播放器 - 懒加载优化 */}
              {isVisible ? (
                <VideoPlayer
                  ref={el => {
                    // 存储视频播放器实例到refs中
                    if (el) {
                      videoPlayerRefs.current.set(item.historyId, el);
                    } else {
                      videoPlayerRefs.current.delete(item.historyId);
                    }
                  }}
                  height={630}
                  src={item.videoUrl}
                  poster={item.firstFrameUrl}
                  controlsList={['play', 'time', 'fullscreen']}
                  onPlay={() => handleVideoPlay(item.historyId, true)}
                  onPause={() => handleVideoPlay(item.historyId, false)}
                  autoPlay={false}
                  preload="metadata" // 优化预加载策略
                />
              ) : (
                // 占位符，显示封面图
                // <div
                //   className={styles.videoPlaceholder}
                //   style={{
                //     height: '630px',
                //     backgroundImage: `url(${item.firstFrameUrl})`,
                //     backgroundSize: 'cover',
                //     backgroundPosition: 'center',
                //     display: 'flex',
                //     alignItems: 'center',
                //     justifyContent: 'center',
                //     color: '#fff',
                //     fontSize: '16px',
                //   }}>
                //   点击加载视频
                // </div>
                <VideoPlaceholder
                  firstFrameUrl={item.firstFrameUrl}
                  historyId={item.historyId}
                  visibleVideos={visibleVideos}
                />
              )}

              {/* 操作按钮 */}
              <div className={styles.videoHistoryActions}>
                {BTN_TYPE.map(button => (
                  <div className={styles.actionButton} key={button.type}>
                    <Button
                      style={{ fontWeight: 400, color: '#fff', opacity: 0.8 }}
                      onClick={e => {
                        e.stopPropagation(); // 阻止事件冒泡
                        handleOptClick(button.type, item);
                      }}
                      icon={
                        <Image
                          className={styles.buttonIcon}
                          src={button.icon}
                          preview={false}
                          draggable={false}
                        />
                      }
                      type={'tertiary'}>
                      {button.text}
                    </Button>
                  </div>
                ))}
              </div>
            </div>
          );
        })}
      </div>
    );
  }
);

VideoHistory.displayName = 'VideoHistory';

export default VideoHistory;
